/**
 * 共享链接管理服务
 * 负责共享链接的创建、管理和访问
 */

import { apiClient, type ShareLinkRequest, type ShareLinkResponse } from './api'
import { authState } from './auth'

// 共享链接信息接口
export interface ShareInfo {
  shareId: string
  shareLink: string
  resourceType: 'folder' | 'note'
  resourceId: number
  password?: string
  expiresAt?: string
  createdAt: string
  accessCount?: number
}

// 本地存储键名
const SHARE_LINKS_KEY = 'linkbook-share-links'

/**
 * 创建共享链接
 * @param resourceType 资源类型
 * @param resourceId 资源ID
 * @param password 密码（可选）
 * @param expiresAt 过期时间（可选）
 * @returns Promise<ShareInfo | null>
 */
export async function createShareLink(
  resourceType: 'folder' | 'note',
  resourceId: number,
  password?: string,
  expiresAt?: string
): Promise<ShareInfo | null> {
  try {
    if (!authState.isLoggedIn) {
      throw new Error('请先登录')
    }

    const shareData: ShareLinkRequest = {
      resourceType,
      resourceId,
      password,
      expiresAt
    }

    const response = await apiClient.createShareLink(shareData)

    if (response.success && response.data) {
      const shareInfo: ShareInfo = {
        shareId: response.data.shareId,
        shareLink: response.data.shareLink,
        resourceType,
        resourceId,
        password,
        expiresAt,
        createdAt: new Date().toISOString(),
        accessCount: 0
      }

      // 保存到本地存储
      saveShareLinkToLocal(shareInfo)

      return shareInfo
    } else {
      throw new Error(response.error || '创建共享链接失败')
    }
  } catch (error) {
    console.error('创建共享链接失败:', error)
    return null
  }
}

/**
 * 获取共享内容
 * @param shareId 共享ID
 * @param password 密码（可选）
 * @returns Promise<any>
 */
export async function getSharedContent(
  shareId: string,
  password?: string
): Promise<any> {
  try {
    const response = await apiClient.getSharedContent(shareId, password)

    if (response.success) {
      return response.data
    } else {
      throw new Error(response.error || '获取共享内容失败')
    }
  } catch (error) {
    console.error('获取共享内容失败:', error)
    throw error
  }
}

/**
 * 删除共享链接
 * @param shareId 共享ID
 * @returns Promise<boolean>
 */
export async function deleteShareLink(shareId: string): Promise<boolean> {
  try {
    if (!authState.isLoggedIn) {
      throw new Error('请先登录')
    }

    const response = await apiClient.deleteShareLink(shareId)

    if (response.success) {
      // 从本地存储中删除
      removeShareLinkFromLocal(shareId)
      return true
    } else {
      throw new Error(response.error || '删除共享链接失败')
    }
  } catch (error) {
    console.error('删除共享链接失败:', error)
    return false
  }
}

/**
 * 获取本地保存的共享链接列表
 * @returns ShareInfo[]
 */
export function getLocalShareLinks(): ShareInfo[] {
  try {
    const stored = localStorage.getItem(SHARE_LINKS_KEY)
    return stored ? JSON.parse(stored) : []
  } catch (error) {
    console.error('获取本地共享链接失败:', error)
    return []
  }
}

/**
 * 保存共享链接到本地存储
 * @param shareInfo 共享信息
 */
function saveShareLinkToLocal(shareInfo: ShareInfo): void {
  try {
    const shareLinks = getLocalShareLinks()
    
    // 检查是否已存在
    const existingIndex = shareLinks.findIndex(link => link.shareId === shareInfo.shareId)
    
    if (existingIndex >= 0) {
      shareLinks[existingIndex] = shareInfo
    } else {
      shareLinks.push(shareInfo)
    }
    
    localStorage.setItem(SHARE_LINKS_KEY, JSON.stringify(shareLinks))
  } catch (error) {
    console.error('保存共享链接到本地失败:', error)
  }
}

/**
 * 从本地存储中删除共享链接
 * @param shareId 共享ID
 */
function removeShareLinkFromLocal(shareId: string): void {
  try {
    const shareLinks = getLocalShareLinks()
    const filteredLinks = shareLinks.filter(link => link.shareId !== shareId)
    localStorage.setItem(SHARE_LINKS_KEY, JSON.stringify(filteredLinks))
  } catch (error) {
    console.error('从本地删除共享链接失败:', error)
  }
}

/**
 * 生成共享链接URL
 * @param shareId 共享ID
 * @returns string
 */
export function generateShareUrl(shareId: string): string {
  const baseUrl = window.location.origin
  return `${baseUrl}/share/${shareId}`
}

/**
 * 复制共享链接到剪贴板
 * @param shareLink 共享链接
 * @returns Promise<boolean>
 */
export async function copyShareLinkToClipboard(shareLink: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(shareLink)
    return true
  } catch (error) {
    console.error('复制到剪贴板失败:', error)
    
    // 降级方案：使用传统方法
    try {
      const textArea = document.createElement('textarea')
      textArea.value = shareLink
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      return true
    } catch (fallbackError) {
      console.error('降级复制方案也失败:', fallbackError)
      return false
    }
  }
}

/**
 * 检查共享链接是否过期
 * @param shareInfo 共享信息
 * @returns boolean
 */
export function isShareLinkExpired(shareInfo: ShareInfo): boolean {
  if (!shareInfo.expiresAt) {
    return false // 没有设置过期时间，永不过期
  }
  
  const expiryDate = new Date(shareInfo.expiresAt)
  const now = new Date()
  
  return now > expiryDate
}

/**
 * 清理过期的共享链接
 */
export function cleanupExpiredShareLinks(): void {
  try {
    const shareLinks = getLocalShareLinks()
    const validLinks = shareLinks.filter(link => !isShareLinkExpired(link))
    
    if (validLinks.length !== shareLinks.length) {
      localStorage.setItem(SHARE_LINKS_KEY, JSON.stringify(validLinks))
      console.log(`清理了 ${shareLinks.length - validLinks.length} 个过期的共享链接`)
    }
  } catch (error) {
    console.error('清理过期共享链接失败:', error)
  }
}

// 定期清理过期的共享链接（每小时执行一次）
setInterval(cleanupExpiredShareLinks, 60 * 60 * 1000)